<?php

namespace app\model;

use think\facade\Db;
use think\Model;

class BasePostLabelsModel extends Model {

    protected $table ="base_post_labels";

    protected $pk = 'base_post_label_id';

    private $cacheKey="base:post:label:id:";

    private $cacheTime=5184000;


    /*
   * 获取total
   * */
    public function getTotal($where=[]){
        return Db::name($this->table)->where($where)->count();
    }



    /*
  * 获取list
  * */
    public function getList($where, $page = null, $limit = null, $orderFields = null)
    {

        $obj = Db::name($this->table)->field($this->pk)->where($where);

        if (!empty($field)) {
            $obj = $obj->field($field);
        }

        if (!empty($page) && !empty($limit)) {
            $obj = $obj->page($page, $limit);
        }

        if (!empty($orderFields)) {
            $obj = $obj->order($orderFields);
        }

        $list = $obj->select();

        if ($list) {
            $return = [];
            foreach ($list as $item) {
                $return[] = $this->getInfo($item[$this->pk]);
            }
            return $return;
        }
        return [];
    }


    public function getInfo($id)
    {
        $cacheKey = $this->cacheKey . $id;
        $redisModel = new RedisModel();
        $info = $redisModel->get($cacheKey);
        if ($info) {
            $info = json_decode($info, true);
        } else {
            $info = Db::name($this->table)->find($id);
            $redisModel->set($cacheKey, json_encode($info, 256), $this->cacheTime);
        }
        return $info;
    }



    public function addOne($data){
        return Db::name($this->table)->insertGetId($data);
    }

    /*
    * 修改运单号
    * */
    public function updateOne($id, $data){
        $where[] = [$this->pk,"=",$id];
        return Db::name($this->table)->where($where)->update($data);
    }



    public function delCache($id)
    {
        $redisModel = new RedisModel();

        return $redisModel->delete($this->cacheKey.$id);
    }


    public function delAllCache()
    {
        $redisModel = new RedisModel();

        return $redisModel->deleteAll($this->cacheKey);
    }
}